import { message } from 'antd';

function request(url, option) {
    const defaultOptions = {
        credentials: 'include'
    };
    const newOptions = { ...defaultOptions, ...option };
    if (newOptions.method === 'POST' || newOptions.method === 'PUT' || newOptions.method === 'DELETE') {
        if (!(newOptions.body instanceof FormData)) {
            newOptions.headers = {
                Accept: 'application/json',
                'Content-Type': 'application/json; charset=utf-8',
                ...newOptions.headers
            };
            newOptions.body = JSON.stringify(newOptions.body);
        } else {
            newOptions.headers = {
                Accept: 'application/json',
                ...newOptions.headers
            };
        }
    }
    return fetch(url, newOptions).then(response => {
        if (newOptions.method === 'DELETE' || response.status === 204) {
            return response.text();
        }
        return response.json();
    });
}
export async function uploadFn(uploadUrl, file, uploadParams, onSuccess, onError) {
    const arr = [];
    arr.push(file.name);
    const params = {
        sysCode: 'OA',
        businessCode: 'SysAvatar',
        fileNames: arr,
        file
    };
    const response = await request(uploadUrl, {
        method: 'POST',
        body: params
    });
    // 返回内容
    if (response.data && response.data.length > 0) {
        const { preUrl, keyName } = response.data[0];
        // const uploadArr = { preUrl, file };
        uploadParams.keyNameAndOpt.unshift(`ADD:${keyName}`);
        // 上传至服务器
        // await uploadToServer(uploadArr, uploadParams, onSuccess, onError);
        onSuccess(preUrl, file, uploadParams);
    } else {
        message.error(response.msg);
        onError();
    }
}

// 上传至服务器
// function uploadToServer(params, uploadParams, onSuccess, onError) {
//     // headers:{'Content-Type':'application/octet-stream'} 很重要！很重要！很重要！
//     const defaultOptions = {
//         method: 'PUT',
//         headers: {
//             'Content-Type': 'application/octet-stream'
//         }
//     };
//     defaultOptions.body = params.file;
//     // 上传进度
//     const progressOptions = {
//         file: params.file
//     };

//     return fetch(params.preUrl, defaultOptions, progressOptions)
//         .then(res => {
//             console.log('上传成功');
//             console.log(res);
//         })
//         .catch(e => e);
// }
